// pages/mina/expressDetail/expressDetail.js
var baseExp = require('../../../common/BaseExpress');
var area = require('../../../utils/area');
Page({
	behaviors: [baseExp],
	data: {
		show_sender_name: false,
		columns_sender_name: [],
		senderIndex: 0,
		senderKey: "",
		senderPhone: '',
		/**货架号 */
		shelve_num: 0,
		total_price: 0,
		tabArr: [{
				title: "冷链",
				express_type: 0,
				/**总金额 */
				total_price: 0,
				/**优惠前金额 */
				total: 0,
				pay_type: 3,
				pay_txt: '选择',
				// company_name: '选择',
				// company_staff_name: '选择',
				// company_staff_mobile: '选择',
				// company_id: 0,
				express_detail: [{
					box_type: "选择",
					box_txt: "选择",
					weight: 0,
					weightArr: [""],
					nums: 1,
					freight: "",
					short_freight: "",
					pack_amount: ""
				}],
			},
			{
				title: "空运",
				express_type: 1,
				total_price: 0,
				/**优惠前金额 */
				total: 0,
				pay_type: 3,
				pay_txt: '选择',
				// company_name: '选择',
				// company_staff_name: '选择',
				// company_staff_mobile: '选择',
				// company_id: 0,
				express_detail: [{
					weight: 0,
					weightArr: [""],
					nums: 1,
					freight: "",
					short_freight: "",
					pack_amount: ""
				}]
			},
			{
				title: "快递",
				express_type: 2,
				total_price: 0,
				/**优惠前金额 */
				total: 0,
				pay_type: 3,
				pay_txt: '选择',
				// company_name: '选择',
				// company_staff_name: '选择',
				// company_staff_mobile: '选择',
				// company_id: 0,
				express_detail: [{
					weight: 0,
					weightArr: [""],
					nums: 1,
					freight: "",
					short_freight: "",
					pack_amount: ""
				}]
			},
			{
				title: "火车",
				express_type: 3,
				total_price: 0,
				/**优惠前金额 */
				total: 0,
				pay_type: 3,
				pay_txt: '选择',
				// company_name: '选择',
				// company_staff_name: '选择',
				// company_staff_mobile: '选择',
				// company_id: 0,
				express_detail: [{
					weight: 0,
					weightArr: [""],
					nums: 1,
					freight: "",
					short_freight: "",
					pack_amount: ""
				}]
			},
		],
		expressInit: {
			box_type: "选择",
			box_txt: "选择",
			weight: 0,
			weightArr: [""],
			nums: 1,
			freight: "",
			short_freight: "",
			pack_amount: ""
		},
		/**选中的寄件索引 */
		expressIndex: 0,
		//包裹大小
		package_size_picker: false,
		PackageSizeChoose: [{
				value: 0,
				text: '小件'
			},
			{
				value: 1,
				text: '中件'
			},
			{
				value: 2,
				text: '大件'
			},
			{
				value: 3,
				text: '特小'
			}
		],
		//付款方式
		payment_picker: false,
		PaymentTypeChoose: [{
				value: 0,
				text: '到付'
			},
			{
				value: 1,
				text: '垫付'
			},
			{
				value: 2,
				text: '未付'
			},
		],
		//冷链公司
		company_picker: false,
		companyArr: [],
		// 重量stepper弹窗
		weight_picker: false,
		//重量选择赋值
		expressPackageWeight: 1,
		//收货人地址，选择了赋值到这里展示
		tab_page: 0,
		shouInfo: '',
		//公司和付款方式
		expressCompany: '',
		/**用户数据 */
		user: {},
		/**提交数据的接口 */
		submitUrl: '/home/staff/order/confirm',
		peopleParam: {
			staff_type: 0
		},
		show_company: false,
		columns_company: [], //物流公司
		companysParam: {
			company_type: 2, //1:物流公司,2:提货物流公司
			express_type: 1 //1:冷链,2:空运,3:快递,4:火车
		},
		areaList: {}, //省市
		showArea: false

	},
	onLoad: function(options) {
		console.log("options", this.data.areaList);
		/**要更新的数据 */
		let menuButtonObject = wx.getMenuButtonBoundingClientRect();
		let newData = {
			navTop: menuButtonObject.top,
			navHeight: menuButtonObject.bottom + 5,
			titleHeight: menuButtonObject.bottom - menuButtonObject.top,
		}
		if (options.uid) {
			this.data.submitUrl = "/home/staff/express/handle";
			newData.user = {
				uid: options.uid,
				name: options.name,
			}
		} else if (!options.shelve_num) {
			return wx.showToast({
				title: '缺少货架参数',
				icon: 'none'
			})
		}
		this.data.shelve_num = options.shelve_num;
		this.data.day = options.day;

		this.setData(newData);
		this.req_companys();
		// this.getPeople();
		// this.getCompanys()
	},

	submit_click() {
		// return console.log(this.data.tabArr);
		let arr = [];
		/**没有数据的物流 */
		let _arr = [];
		this.data.tabArr.map(val => {
			// !val.total_price ? val.total_price = val.total : '';
			if (val.total > 0) {
			  !val.total_price?val.total_price=val.total:'';
			  if (val.express_type) { //非冷链，重量必填
			    let express_detail=[];
				  val.express_detail.map(express=>{
					  if(express.weight){
						  express_detail.push(express);
					  }
				  });
				val.express_detail=express_detail;
			  }
			  arr.push(val);
			} else {
			  _arr.push(val);
			}
			// arr.push(val);
			// if (val.sender_name && val.delivery_name) {
			// 	!val.total_price ? val.total_price = val.total : '';
			// 	// val.express_detail.map(express => {
			// 	//   let weightArr=[];
			// 	//   express.weightArr.map(num=>{
			// 	//     weightArr.
			// 	//   });
			// 	// });
			// 	arr.push(val);
			// } else {
			// 	_arr.push(val);
			// }
			// if (val.total > 0) {
			//   !val.total_price?val.total_price=val.total:'';
			//   arr.push(val);
			// } else {
			//   _arr.push(val);
			// }
		})
		if (!arr.length) {
			return wx.showToast({
				title: '请填写物流价格等信息',
				icon: 'none'
			})
		}
		console.log("编辑好得数据", arr)
		if (_arr.length) {
			let that = this;
			return wx.showModal({
				cancelText: '确认提交',

				confirmText: '继续添加',
				content: '是否需要继续添加 ' + _arr[0].title + " 等物流信息",
				showCancel: true,
				success: (res) => {
					if (res.confirm) {
						that.setData({
							tab_page: _arr[0].express_type
						})
					} else if (res.cancel) {
						that.req_confirm(arr);
					}
				},
			})
		}
		this.req_confirm(arr);
	},
	req_confirm(arr) {
		this.request({
			url: this.data.host + this.data.submitUrl,
			method: 'POST',
			loadingTip: '提交中...',
			data: {
				day: this.data.day,
				shelve_num: this.data.shelve_num,
				express: JSON.stringify(arr),
				uid: this.data.user.uid
			},
		}, res => {
			// console.log("提交成功", res);
			wx.showToast({
				title: '确认成功',
			});
			wx.navigateBack({
				delta: 1,
			})
		})
	},
	req_companys() {
		this.request({
			url: this.data.host + '/home/staff/company?limit=9999',
		}, res => {
			// console.log("cls:公司",res);
			let arr = [];
			res.data.map(val => {
				arr.push({
					value: val.company_id,
					text: val.title
				})
			})
			this.setData({
				companyArr: arr
			})
		})

	},
	onChange(e) {
		var companysParam=this.data.companysParam
		companysParam.express_type=e.detail.index+1
		this.setData({
			tab_page: e.detail.index
		})
		console.log()
	},
	/**寄件想起输入：金额，运费，包装 */
	express_input(e) {
		// console.log("cls：输入框", e);
		let key = "tabArr[" + this.data.tab_page + "].express_detail[" + e.currentTarget.dataset.index + "]." +
			e.currentTarget.dataset.key;
		this.setData({
			[key]: e.detail,
		});
		// console.log("新", this.data.tabArr);
		this.update_total();
	},
	weight_input(e) {
		let i = e.currentTarget.dataset.express;
		let weightArr = this.data.tabArr[this.data.tab_page].express_detail[i].weightArr;
		if (e.detail.value) {
			weightArr[e.currentTarget.dataset.weight] = e.detail.value;
		} else if (weightArr.length > 1) {
			weightArr.splice(e.currentTarget.dataset.weight, 1);
		}
		this.setData({
			[`tabArr[${this.data.tab_page}].express_detail[${i}].weightArr`]: weightArr
		})
		this.update_total();
	},
	/**添加重量件 */
	add_weight(e) {
		let i = e.currentTarget.dataset.express;
		let weightArr = this.data.tabArr[this.data.tab_page].express_detail[i].weightArr;
		weightArr.push("");
		this.setData({
			[`tabArr[${this.data.tab_page}].express_detail[${i}].weightArr`]: weightArr
		})
	},
	/**
	 * 总价输入
	 */
	price_input(e) {
		console.log("price_input", e);
		let tab_page = this.data.tab_page * 1;
		let tab = this.data.tabArr[tab_page];
		//校验数据
		let errTxt = "";
		tab.total_price = e.detail;
		if (!tab.sender_name || !tab.delivery_name) {
			errTxt = "请先完善寄件人和提件人信息\n";
		}
		for (let i = 0; i < tab.express_detail.length; i++) {
			let express = tab.express_detail[i];
			if (tab.express_type == 0 && express.box_txt == "选择") {
				errTxt += "提件大小必选\n";
				break;
			}
			if (!express.freight) {
				errTxt += "提件金额与包装费必填\n";
				break;
			}
		}
		if (errTxt) {
			wx.hideKeyboard({
				complete: res => {
					console.log('hideKeyboard res', res)
				}
			})
			this.setData({
				[`tabArr[${tab_page}].total_price`]: 0,
			})
			return wx.showModal({
				showCancel: false,
				content: errTxt
			})
		}
		let total_price = 0;
		this.data.tabArr.map(val => {
			val.total_price ? total_price += val.total_price * 1 : total_price += val.total * 1;

		})
		this.setData({
			[`tabArr[${tab_page}].total_price`]: e.detail,
			total_price: total_price
		})
	},
	/**更新总金额显示 */
	update_total() {
		let total = 0;
		let total_price = 0;
		let tab_page = this.data.tab_page * 1;
		let val = this.data.tabArr[tab_page];
		val.express_detail.map(express => {
			// if (tab_page == 0 && express.box_txt == "选择") { //如果是冷链，必选大小
			//   return;
			// }
			if (val.express_type) { //非冷链，需要计算重量
				let weight = 0;
				let nums = 0;
				// console.log("weightArr",express.weightArr);
				let weight_arr = [];
				express.weightArr.map(num => {
					if (num) {
						weight += num * 1;
						nums++;
						weight_arr.push(num);
					}

				})
				// console.log("重量统计",weight,nums)
				if (!weight || !nums) {
					return;
				}
				express.weight_arr = weight_arr;
				express.weight = weight;
				express.nums = nums;
				// console.log("express.nums",express.nums);
				// console.log("express.weight_arr",express.weight_arr)
				// console.log("express.weight",express.weight)
				total += express.freight * 1 * express.weight;
			} else { //为冷链,必须选中盒子大小
				if (express.ox_txt == "选择") {
					return;
				}
				total += express.freight * express.nums;
			}
			express.short_freight ? total += express.short_freight * express.nums : "";
			express.pack_amount ? total += express.pack_amount * express.nums : "";
			val.total = total;
		})
		this.data.tabArr.map(tab => {
			tab.total_price * 1 ? total_price += tab.total_price * 1 : total_price += tab.total * 1;
		})
		this.setData({
			[`tabArr[${tab_page}].total`]: total.toFixed(2),
			total_price: total_price.toFixed(2)
		});
	},
	catch_input(){},//输入框点击防止冒泡事件
	input_change(e) {

		let dataset = e.currentTarget.dataset;
		// console.log(dataset.index,dataset.key,e.detail.value);
		if(dataset.key=="sender_name" || dataset.key=="sender_mobile"){//寄件人
			delete this.data.tabArr[dataset.index].sender_id
		}else if(dataset.key=="delivery_name" || dataset.key=="delivery_mobile"){//提件人
			delete this.data.tabArr[dataset.index].delivery_id
		}else if(dataset.key=="company_name"){//物流公司
			delete this.data.tabArr[dataset.index].company_id
		}else if(dataset.key=="company_staff_name" || dataset.key=="company_staff_mobile"){
			delete this.data.tabArr[dataset.index].company_staff_id
		}
		
		
		this.data.tabArr[dataset.index][dataset.key] = e.detail.value || e.detail;
	},
	//查询寄件人
	getPeople() {
		this.request({
			url: this.data.host + "/home/staff/company/staff",
			data: this.data.peopleParam,
			method: "GET"
		}, res => {
			// console.log("查询寄件人", res)
			let arr = [];
			res.data.map(val => {
				arr.push({
					value: val.staff_id,
					text: val.name,
					phone: val.phone
				})
			})

			this.setData({
				columns_sender_name: arr,
				show_sender_name: true,

			})
		})
	},
	//查询物流公司
	getCompanys() {
		this.request({
			url: this.data.host + "/home/staff/company/items",
			data: this.data.companysParam,
			method: "GET"
		}, res => {
			// console.log("查询物流公司", res)
			let arr = [];
			res.data.map(val => {
				arr.push({
					value: val.company_id,
					text: val.title,
					phone: val.phone
				})
			})
			this.setData({
				show_company: true,
				columns_company: arr
			})
		})
	},
	//查询物流地区省
	getProvince(){
		this.request({
			url: this.data.host + "/home/staff/company/province",
			data: {
				company_type:this.data.companysParam.company_type,
				company_id:this.data.peopleParam.company_id,
				express_type:this.data.companysParam.express_type,
			},
			method: "GET"
		}, res => {
			console.log("查询物流地区", res)
			var list=res.data
			var province_list={}
			list.map((value,index)=>{
				province_list[value.province_code] = value.province;
			})
			console.log("滚动选择", province_list)
			var areaList=this.data.areaList
			areaList.province_list=province_list
			this.setData({
				areaList:areaList
			})
			this.getCity(list[0].province_code)
		})
	},
	//查询物流地区市（
	getCity(code){
		this.request({
			url: this.data.host + "/home/staff/company/city",
			data: {
				company_type:this.data.companysParam.company_type,
				company_id:this.data.peopleParam.company_id,
				express_type:this.data.companysParam.express_type,
				province_code:code
			},
			method: "GET"
		}, res => {
			console.log("查询物流地区市", res)
			var list=res.data
			var city_list={}
			list.map((value,index)=>{
				city_list[value.city_code]=value.city
			})
			console.log("滚动选择", city_list)
			var areaList=this.data.areaList
			console.log("*****areaList******", areaList)
			areaList.city_list=city_list
			this.setData({
				areaList:areaList,
				showArea: true,
			})
		})
	},
	changeArea(e){
		console.log("滚动选择", e)
		if(e.detail.index==0){
			this.getCity(e.detail.values[0].code)
		}
	},
	//选择寄件人
	select_sender_name(e) {
		// console.log("选择寄件人", e)
		var peopleParam = {
			staff_type: 0
		}
		this.setData({
			peopleParam:peopleParam,
			senderIndex: e.currentTarget.dataset.index,
			senderKey: e.currentTarget.dataset.key,
			senderPhone: e.currentTarget.dataset.phone,
			peopleid: e.currentTarget.dataset.peopleid
		})
		this.getPeople()
	},
	onChangeSender(e) {
		// console.log("选择寄件人a", e)
		// console.log("选择寄件人b", this.data.columns_sender_name)
		if(!e.detail.value.text&& !e.detail.value.phone && !e.detail.value.value){
			wx.showToast({
			  title: '请选择人员',
			  icon: 'none',
			  duration: 2000
			})
			return;
		}
		var tabArr = this.data.tabArr
		tabArr[this.data.senderIndex][this.data.senderKey] = e.detail.value.text
		tabArr[this.data.senderIndex][this.data.senderPhone] = e.detail.value.phone
		tabArr[this.data.senderIndex][this.data.peopleid] = e.detail.value.value
		// console.log("选择寄件人", this.data.tabArr);
		this.setData({
			show_sender_name: false,
			tabArr: tabArr
		})
	},
	//选择物流公司
	clickdelivery_name(e) {
		var peopleParam = this.data.peopleParam
		var companysParam=this.data.companysParam
		peopleParam.staff_type = 1 //0:寄件人,1:物流公司人
		if(this.data.user.uid){
			companysParam.company_type=2
		}else{
			companysParam.company_type=e.currentTarget.dataset.type
		}
		
		this.setData({
			// show_company: true,
			peopleParam: peopleParam,
			companysParam:companysParam,
			senderIndex: e.currentTarget.dataset.index,
			senderKey: e.currentTarget.dataset.key,
			senderPhone: e.currentTarget.dataset.phone,
			senderCompany: e.currentTarget.dataset.company,
			peopleid: e.currentTarget.dataset.peopleid
		})
		this.getCompanys()
	},
	//确定物流公司--选择省市
	onChangeCompany(e) {
		// console.log("选择的物流公司", e)
		var peopleParam = this.data.peopleParam
		peopleParam.company_id = e.detail.value.value
		var tabArr = this.data.tabArr
		
		if(this.data.senderKey=="company_staff_name"){
			tabArr[this.data.senderIndex]['company_id'] = e.detail.value.value
			tabArr[this.data.senderIndex][this.data.senderCompany] = e.detail.value.text
		}
		this.getProvince()
		this.selectComponent("#myArea").reset()//重置地区
		this.setData({
			areaList:{},
			show_company: false,
			peopleParam: peopleParam,
			tabArr:tabArr
		})
	},
	//选择物流公司，查询人员，选择人员弹框
	area_ok(e) {
		// console.log("选择的地区", e)
		var peopleParam = this.data.peopleParam
		peopleParam.province_code = e.detail.values[0].code
		peopleParam.city_code = e.detail.values[1].code
		// console.log("param", peopleParam)
		this.setData({
			showArea: false,
			peopleParam: peopleParam
		})
		this.getPeople()
	},
	onClose() {
		this.setData({
			package_size_picker: false,
			weight_picker: false,
			payment_picker: false,
			company_picker: false,
			show_sender_name: false,
			show_company: false,
			showArea: false
		})
	},
	//关闭区域选择，打开公司选择
	onCloseArea(){
		this.setData({
			show_company: true,
			showArea: false
		})
	},
	//关闭选择人员,打开选择区域
	onClosePeople(){
		if(this.data.peopleParam.staff_type==0){
			//选择寄件人
			this.setData({
				show_sender_name: false
			})
		}else{
			//提件人或者物流人员
			this.setData({
				show_sender_name: false,
				showArea: true
			})
		}
	},
	choosePackage(e) {
		// console.log("choosePackage",e);
		this.data.expressIndex = e.currentTarget.dataset.index;
		this.setData({
			package_size_picker: true
		})
	},
	/**选中寄件大小 */
	size_ok(e) {

		let key = "tabArr[" + this.data.tab_page + "].express_detail[" + this.data.expressIndex + "].box_type";
		let txt = "tabArr[" + this.data.tab_page + "].express_detail[" + this.data.expressIndex + "].box_txt";
		this.setData({
			[key]: e.detail.value.value,
			[txt]: e.detail.value.text,
			package_size_picker: false
		});
		this.update_total()

	},
	pay_picker(e) {
		let tab_page = this.data.tab_page;

		this.setData({
			[`tabArr[${tab_page}].pay_type`]: e.detail.value.value,
			[`tabArr[${tab_page}].pay_txt`]: e.detail.value.text,
			payment_picker: false
		})
	},
	company_picker_ok(e) {

		let tab_page = this.data.tab_page;
		this.setData({
			[`tabArr[${tab_page}].company_name`]: e.detail.value.text,
			[`tabArr[${tab_page}].company_id`]: e.detail.value.value,
			company_picker: false
		})
	},
	weight_change(e) {
		let i = e.currentTarget.dataset.index;
		let key = "tabArr[" + this.data.tab_page + "].express_detail[" + i + "].weight";
		this.setData({
			[key]: e.detail
		});
		this.update_total()
	},
	StepperChange(e) {

		let i = e.currentTarget.dataset.index;
		let key = "tabArr[" + this.data.tab_page + "].express_detail[" + i + "].nums";
		this.setData({
			[key]: e.detail
		});
		this.update_total();

	},

	//添加寄售按钮
	addPackageForm() {
		let tab_page = this.data.tab_page;
		this.data.tabArr[tab_page].express_detail.push(JSON.parse(JSON.stringify(this.data.expressInit)));
		this.setData({
			[`tabArr[${tab_page}].express_detail`]: this.data.tabArr[tab_page].express_detail
		})

	},


	showCompanyPicker() {
		let tab_page = this.data.tab_page
		let ChainCompany = this.data.ChainCompany
		let flyCompany = this.data.flyCompany
		let expressCompanyArr = this.data.expressCompanyArr
		this.setData({
			companyPickerCloumns: tab_page == 0 ? ChainCompany : tab_page == 1 ? flyCompany :
				expressCompanyArr,
			company_picker: true,
		})
	},
	showPaymentPicker() {
		this.setData({
			payment_picker: true,
		})
	},

	PackageWeightChange(e) {
		console.log('重量stepper改变', e.detail)
	},



	//删除寄售卡片按钮
	minsTap(e) {
		let tab_page = this.data.tab_page;
		let tabArr = this.data.tabArr;
		let index = e.currentTarget.dataset.index;

		if (tabArr[tab_page].express_detail.length < 2) {
			return wx.showToast({
				title: '至少添加一个寄件信息',
			})
		}
		tabArr[tab_page].express_detail.splice(index, 1);
		this.setData({
			[`tabArr[${tab_page}].express_detail`]: tabArr[tab_page].express_detail
		})
		// let index = e.currentTarget.dataset.index
		// console.log(index)
		// if (index > 0) {
		//   let tab_page = this.data.tab_page
		//   let arr = tab_page == 0 ? this.data.packageFieldArr : this.data.packageFieldArrFly
		//   let newArr = arr.splice(index, 1)
		//   this.setData({
		//     [tab_page == 0 ? 'packageFieldArr' : 'packageFieldArrFly']: newArr
		//   })
		// }
	},


})
